package cn.lili.modules.union.serviceimpl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.event.TransactionCommitSendMQEvent;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.exchange.AmqpExchangeProperties;
import cn.lili.modules.constant.CommonConstant;
import cn.lili.modules.distribution.client.DistributionClient;
import cn.lili.modules.distribution.entity.dos.Distribution;
import cn.lili.modules.distribution.entity.enums.DistributionStatusEnum;
import cn.lili.modules.distribution.entity.vos.DistributionVO;
import cn.lili.modules.distribution.entity.vos.HomeResult;
import cn.lili.modules.member.client.UserClient;
import cn.lili.modules.member.entity.dos.*;
import cn.lili.modules.member.entity.dto.NumberOfOwnerDTO;
import cn.lili.modules.member.entity.dto.UnionAddDTO;
import cn.lili.modules.member.entity.dto.UnionMemberCountDTO;
import cn.lili.modules.member.entity.dto.UnionMemberDetailDTO;
import cn.lili.modules.member.entity.enums.UnionMemberStatusEnum;
import cn.lili.modules.member.entity.vo.NumberOfOwners;
import cn.lili.modules.member.entity.vo.NumberOfOwnersReq;
import cn.lili.modules.member.service.UserService;
import cn.lili.modules.operationcenter.client.OperationCenterClient;
import cn.lili.modules.operationcenter.entity.dos.OperationCenter;
import cn.lili.modules.order.order.client.OrderClient;
import cn.lili.modules.order.order.client.OrderItemClient;
import cn.lili.modules.order.order.entity.dos.Order;
import cn.lili.modules.order.order.entity.dos.OrderFlow;
import cn.lili.modules.order.order.entity.dto.OrderFlowDTO;
import cn.lili.modules.order.order.entity.vo.OrderItemViewVO;
import cn.lili.modules.order.order.entity.vo.PerformanceDetailVO;
import cn.lili.modules.order.order.entity.vo.UnionOrderParams;
import cn.lili.modules.union.mapper.UnionMapper;
import cn.lili.modules.union.mapper.UnionMemberApplyMapper;
import cn.lili.modules.union.mapper.UnionMemberMapper;
import cn.lili.modules.union.service.UnionMemberApplyService;
import cn.lili.modules.union.service.UnionMemberService;
import cn.lili.mybatis.util.PageUtil;
import cn.lili.routing.UnionRoutingKey;
import cn.lili.util.GoodsSkuPriceUtil;
import cn.lili.util.HomeResultUtil;
import cn.lili.util.ToolUtil;
import cn.wildfirechat.pojos.PojoGroupMember;
import cn.wildfirechat.proto.ProtoConstants;
import cn.wildfirechat.sdk.GroupAdmin;
import cn.wildfirechat.sdk.model.IMResult;
import com.api.UserApi;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beust.ah.A;
import com.pojos.OpenAppUser;
import kotlin.jvm.internal.Lambda;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.*;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class UnionMemberServiceImpl extends ServiceImpl<UnionMemberMapper, UnionMember> implements UnionMemberService {

    private final UserService userService;

    @Resource
    private UnionMapper unionMapper;

    private final ApplicationEventPublisher applicationEventPublisher;

    private final AmqpExchangeProperties amqpExchangeProperties;

    private final OrderClient orderClient;

    private final OrderItemClient orderItemClient;

    private final RedissonClient redissonClient;

    @Resource
    private UnionMemberApplyMapper unionMemberApplyMapper;

    @Resource
    private UnionMemberMapper unionMemberMapper;

    private final UserApi userApi;

    private final OperationCenterClient operationCenterClient;

    private final DistributionClient distributionClient;

    private final UserClient userClient;

    /**
     * 分页查询工会成员信息
     *
     * @param unionMemberParams
     * @param pageVO
     * @return
     */
    @Override
    public Page<UnionMember> getByPage(UnionMember unionMemberParams, PageVO pageVO) {
        /*QueryWrapper<UnionMemberApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_flag", false);
        queryWrapper.eq(StringUtils.isNotEmpty(unionMemberParams.getUnionId()), "union_id", unionMemberParams.getUnionId());
        queryWrapper.eq(StringUtils.isNotEmpty(unionMemberParams.getMemberId()), "member_id", unionMemberParams.getMemberId());
        queryWrapper.like(StringUtils.isNotEmpty(unionMemberParams.getMemberName()), "member_name", unionMemberParams.getMemberName());
        queryWrapper.eq(StringUtils.isNotEmpty(unionMemberParams.getStatus()), "status", unionMemberParams.getStatus());
        //queryWrapper.having("monthMoney >= {0} and monthMoney <= {1}", unionMemberParams.getStartMoney(), unionMemberParams.getEndMoney());
        queryWrapper.groupBy("member_id");
        queryWrapper.orderByDesc("create_time");*/
        Page<UnionMember> page = this.baseMapper.getByPage(PageUtil.initPage(pageVO), unionMemberParams);
        if (!page.getRecords().isEmpty()) {
            page.getRecords().forEach(unionMember -> {
                // 成员下级人数
                Integer count = userService.getCountLowerByParentId(unionMember.getMemberId());
                unionMember.setChildCount(count);

                // 成员上月业绩
                Double lastMonthMoney = orderClient.getLastMonthMoneyByMemberId(unionMember.getMemberId());
                unionMember.setLastMonthMoney(lastMonthMoney == null ? 0D : lastMonthMoney);

                // 成员本月业绩
                Double monthMoney = orderClient.getCurrentMonthMoneyByMemberId(unionMember.getMemberId());
                unionMember.setMonthMoney(monthMoney == null ? 0D : monthMoney);

                // 工会成员ID和昵称改成从fy获取
                User user = userClient.getById(unionMember.getMemberId());
                if (null != user) {
                    unionMember.setFyAccount(user.getAccount());
                    unionMember.setMemberName(user.getFyName());
                }
            });
        }
        return page;
    }

    /**
     * 根据工会ID和成员ID查询工会成员
     *
     * @param unionId
     * @param memberId
     * @return
     */
    @Override
    public UnionMember getByUnionMemberId(String unionId, String memberId) {
        LambdaQueryWrapper<UnionMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UnionMember::getUnionId, unionId);
        queryWrapper.eq(UnionMember::getMemberId, memberId);
        queryWrapper.eq(UnionMember::getDeleteFlag, false);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }


    /**
     * 根据成员ID查询工会成员
     *
     * @param memberId
     * @return
     */
    @Override
    public UnionMember getByUnionMemberId(String memberId) {
        LambdaQueryWrapper<UnionMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UnionMember::getMemberId, memberId);
        queryWrapper.eq(UnionMember::getDeleteFlag, false);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }

    /**
     * 获取工会成员人数
     *
     * @param unionId
     * @return
     */
    @Override
    public long getCountByUnionId(String unionId) {
        LambdaQueryWrapper<UnionMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UnionMember::getUnionId, unionId);
        queryWrapper.eq(UnionMember::getStatus, UnionMemberStatusEnum.PASS.name());
        queryWrapper.eq(UnionMember::getDeleteFlag, false);
        return this.count(queryWrapper);
    }

    /**
     * 添加工会成员
     *
     * @param unionAddDTO
     */
    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void addMember(UnionAddDTO unionAddDTO) {
        if (unionAddDTO.getMemberList().isEmpty() || StringUtils.isEmpty(unionAddDTO.getId())) {
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        addUnionMember(unionAddDTO, unionAddDTO.getId());
    }

    /**
     * 添加工会成员
     *
     * @param unionAddDTO
     * @param id
     */
    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void addUnionMember(UnionAddDTO unionAddDTO, String id) {
        List<UnionLog> unionLogList = Lists.newArrayList();
        List<UnionMember> unionMemberList = Lists.newArrayList();
        List<PojoGroupMember> groupMemberList = Lists.newArrayList();
        if (!unionAddDTO.getMemberList().isEmpty()) {
            Union union = unionMapper.selectById(id);
            for (String memberId : unionAddDTO.getMemberList()) {
                // 是否有会长用户
                Union checkChairMan = getByMemberId(memberId);
                if (null != checkChairMan) {
                    throw new ServiceException("用户[" + union.getChairmanName() + "]已加入其他工会");
                }
                UnionMember member = getByUnionMemberId(memberId);
                if (null != member) {
                    throw new ServiceException("用户[" + member.getMemberName() + "]已加入其他工会");
                }
                User user = userService.getById(memberId);

                if (null != user) {
                    if (StringUtils.isNotEmpty(user.getUnionId()) && !user.getUnionId().equals(id)) {
                        quitGroup(user, union);
                        UnionLog unionLog = UnionLog.builder()
                                .operationRemark("用户：" + user.getUsername() + "[" + user.getId() + "]，退出工会")
                                .createTime(new Date())
                                .unionId(id)
                                .operationUserId(UserContext.getCurrentId())
                                .operationUserName(Objects.requireNonNull(UserContext.getCurrentUser()).getUsername())
                                .build();
                        unionLogList.add(unionLog);
                    }
                    user.setUnionId(id);
                    userService.updateById(user);

                    UnionMember unionMember = new UnionMember();
                    unionMember.setMemberId(user.getId());
                    unionMember.setMemberName(user.getUsername());
                    unionMember.setJoinTime(new Date());
                    unionMember.setStatus(UnionMemberStatusEnum.PASS.name());
                    unionMember.setUnionId(id);
                    unionMemberList.add(unionMember);

                    UnionMemberApply unionMemberApply = new UnionMemberApply();
                    unionMemberApply.setMemberId(user.getId());
                    unionMemberApply.setMemberName(user.getUsername());
                    unionMemberApply.setJoinTime(new Date());
                    unionMemberApply.setStatus(UnionMemberStatusEnum.PASS.name());
                    unionMemberApply.setUnionId(id);
                    unionMemberApplyMapper.insert(unionMemberApply);

                    try {
                        if (StringUtils.isNotEmpty(user.getOpenId())) {
                            OpenAppUser openAppUser = userApi.getUserinfoByOpenId(user.getOpenId());
                            if (null != openAppUser) {
                                PojoGroupMember groupMember = new PojoGroupMember();
                                groupMember.setMember_id(openAppUser.getUId());
                                groupMember.setType(ProtoConstants.GroupMemberType.GroupMemberType_Normal);
                                groupMemberList.add(groupMember);
                            }
                        }
                    } catch (Exception e) {
                        log.error("异常：{}", e.getMessage());
                    }


                    UnionLog unionLog = UnionLog.builder()
                            .operationRemark("添加成员：" + user.getUsername() + "[" + user.getId() + "]")
                            .createTime(new Date())
                            .unionId(id)
                            .operationUserId(UserContext.getCurrentId())
                            .operationUserName(Objects.requireNonNull(UserContext.getCurrentUser()).getUsername())
                            .build();

                    unionLogList.add(unionLog);
                }
            }

            addGroup(groupMemberList, union);
        }
        this.saveBatch(unionMemberList);

        if (!unionLogList.isEmpty()) {
            applicationEventPublisher.publishEvent(
                    TransactionCommitSendMQEvent.builder()
                            .source("UNION_LOG")
                            .exchange(amqpExchangeProperties.getUnion())
                            .routingKey(UnionRoutingKey.BATCH_ADD_UNION_LOG)
                            .message(unionLogList)
                            .build());
        }
    }

    private void addGroup(List<PojoGroupMember> groupMemberList, Union union) {
        // 加入群组
        if (!groupMemberList.isEmpty()) {
            try {
                User user = userService.getById(union.getChairmanId());
                OpenAppUser openAppUser = userApi.getUserinfoByOpenId(user.getOpenId());
                GroupAdmin.addGroupMembers(openAppUser.getUId(), union.getGroupId(), groupMemberList, new ArrayList<Integer>() {{
                    add(0);
                }}, null);
            } catch (Exception e) {
                log.error("添加群组成员失败:{}", e.getMessage());
            }
        }
    }

    /**
     * 踢出工会成员
     *
     * @param unionAddDTO
     */
    @Override
    public void deleteUnionMember(UnionAddDTO unionAddDTO) {
        if (unionAddDTO.getMemberList().isEmpty() || StringUtils.isEmpty(unionAddDTO.getId())) {
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        List<UnionLog> unionLogList = Lists.newArrayList();
        if (!unionAddDTO.getMemberList().isEmpty()) {
            // 解除用户与工会绑定关系
            LambdaUpdateWrapper<UnionMember> memberLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            memberLambdaUpdateWrapper.in(UnionMember::getMemberId, unionAddDTO.getMemberList());
            memberLambdaUpdateWrapper.set(UnionMember::getDeleteFlag, true);
            this.update(memberLambdaUpdateWrapper);

            // 解除用户与工会绑定关系
            LambdaUpdateWrapper<UnionMemberApply> applyLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            applyLambdaUpdateWrapper.in(UnionMemberApply::getMemberId, unionAddDTO.getMemberList());
            applyLambdaUpdateWrapper.eq(UnionMemberApply::getUnionId, unionAddDTO.getId());
            applyLambdaUpdateWrapper.eq(UnionMemberApply::getStatus, UnionMemberStatusEnum.PASS.name());
            applyLambdaUpdateWrapper.set(UnionMemberApply::getDeleteFlag, true);
            unionMemberApplyMapper.update(null, applyLambdaUpdateWrapper);

            // 解除用户绑定工会关系
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.in(User::getId, unionAddDTO.getMemberList());
            updateWrapper.set(User::getUnionId, null);
            userService.update(updateWrapper);

            Union union = unionMapper.selectById(unionAddDTO.getId());
            for (String memberId : unionAddDTO.getMemberList()) {
                User user = userService.getById(memberId);
                if (null != user) {
                    quitGroup(user, union);

                    UnionLog unionLog = UnionLog.builder()
                            .operationRemark("[" + user.getUsername() + "]" + ",离开工会")
                            .createTime(new Date())
                            .unionId(unionAddDTO.getId())
                            .operationUserId(UserContext.getCurrentId())
                            .operationUserName(Objects.requireNonNull(UserContext.getCurrentUser()).getUsername())
                            .build();

                    unionLogList.add(unionLog);
                }
            }
        }
        if (!unionLogList.isEmpty()) {
            applicationEventPublisher.publishEvent(
                    TransactionCommitSendMQEvent.builder()
                            .source("UNION_LOG")
                            .exchange(amqpExchangeProperties.getUnion())
                            .routingKey(UnionRoutingKey.BATCH_ADD_UNION_LOG)
                            .message(unionLogList)
                            .build());
        }
    }

    private void quitGroup(User user, Union union) {
        try {
            // 退出群组
            if (StringUtils.isNotEmpty(user.getOpenId())) {
                OpenAppUser openAppUser = userApi.getUserinfoByOpenId(user.getOpenId());
                if (null != openAppUser) {
                    GroupAdmin.quitGroup(openAppUser.getUId(), union.getGroupId(), new ArrayList<Integer>() {{
                        add(0);
                    }}, null);
                }
            }
        } catch (Exception e) {
            log.error("退群异常：{}", e.getMessage());
        }
    }

    /**
     * 查询用户是不是会长
     *
     * @param memberId
     * @return
     */
    public Union getByMemberId(String memberId) {
        LambdaQueryWrapper<Union> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Union::getChairmanId, memberId);
        queryWrapper.last("limit 1");
        return unionMapper.selectOne(queryWrapper);
    }


    @Override
    public UnionMemberCountDTO getCountData(String unionId) {
        LambdaQueryWrapper<UnionMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UnionMember::getUnionId, unionId);
        queryWrapper.last("limit 1");
        Long totals = this.baseMapper.selectCount(queryWrapper);

        Date monthStart = DateUtil.beginOfMonth(new Date());
        Date monthEnd = DateUtil.endOfMonth(new Date());
        LambdaQueryWrapper<UnionMember> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(UnionMember::getUnionId, unionId);
        queryWrapper1.ge(UnionMember::getJoinTime, monthStart);
        queryWrapper1.le(UnionMember::getJoinTime, monthEnd);
        Long monthTotal = this.baseMapper.selectCount(queryWrapper1);

        Date lastMonth = DateUtil.lastMonth();
        Date lastMonthStart = DateUtil.beginOfMonth(lastMonth);
        Date lastMonthEnd = DateUtil.endOfMonth(lastMonth);
        LambdaQueryWrapper<UnionMember> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(UnionMember::getUnionId, unionId);
        queryWrapper2.ge(UnionMember::getJoinTime, lastMonthStart);
        queryWrapper2.le(UnionMember::getJoinTime, lastMonthEnd);
        Long lastMonthAdd = this.baseMapper.selectCount(queryWrapper2);

        UnionMemberCountDTO countDTO = new UnionMemberCountDTO();
        countDTO.setLastMonthAdd(lastMonthAdd);
        countDTO.setMonthAdd(monthTotal);
        countDTO.setTotals(totals);

        return countDTO;
    }

    /**
     * 分页查询工会成员信息
     *
     * @param unionId 工会ID
     * @param pageVO
     * @return
     */
    @Override
    public Page<UnionMember> getMembersByPage(String unionId, PageVO pageVO) {
        QueryWrapper<UnionMember> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("union_id", unionId);
        queryWrapper.eq("delete_flag", false);
        queryWrapper.eq("status", UnionMemberStatusEnum.PASS.name());
        queryWrapper.groupBy("member_id");
        Page<UnionMember> page = this.page(PageUtil.initPage(pageVO), queryWrapper);
        if (!page.getRecords().isEmpty()) {
            List<String> memberIdList = page.getRecords().stream().map(item -> item.getMemberId()).collect(Collectors.toList());
            List<User> userList = userService.findByIdList(memberIdList);

            page.getRecords().forEach(unionMember -> {
                User chairman = userList.stream().filter(item -> item.getId().equals(unionMember.getMemberId())).findFirst().orElse(null);
                if (null != chairman) {
                    unionMember.setMemberName(chairman.getNickName());
                    unionMember.setMemberHead(chairman.getFace());
                }
                // 成员下级人数
                Integer count = userService.getCountLowerByParentId(unionMember.getMemberId());
                unionMember.setChildCount(count);

                // 成员上月业绩
                Double lastMonthMoney = orderClient.getLastMonthMoneyByMemberId(unionMember.getMemberId());
                unionMember.setLastMonthMoney(lastMonthMoney == null ? 0D : lastMonthMoney);

                // 成员本月业绩
                Double monthMoney = orderClient.getCurrentMonthMoneyByMemberId(unionMember.getMemberId());
                unionMember.setMonthMoney(monthMoney == null ? 0D : monthMoney);

                // 工会成员ID和昵称改成从fy获取
                User user = userClient.getById(unionMember.getMemberId());
                if (null != user) {
                    //unionMember.setMemberId(user.getAccount());
                    unionMember.setMemberName(user.getFyName());
                }
            });
        }
        return page;
    }

    /**
     * 查询工会成员本月业绩
     *
     * @return
     */
    @Override
    public Page<OrderFlowDTO> getCurrentMonthByUnionMember(UnionOrderParams params) {
        return orderClient.getCurrentMonthByUnionMember(params);
    }

    /**
     * 根据工会成员统计本月已结算金额、待结算金额、退单金额
     *
     * @return
     */
    @Override
    public PerformanceDetailVO getCurrentMonthStatisticsByMember(UnionOrderParams params) {
        return orderClient.getCurrentMonthStatisticsByMember(params);
    }

    /**
     * 查询工会成员上月业绩
     *
     * @return
     */
    @Override
    public Page<OrderFlowDTO> getLastMonthByUnionMember(UnionOrderParams params) {
        return orderClient.getLastMonthByUnionMember(params);
    }

    /**
     * 根据工会成员统计上月已结算金额、待结算金额、退单金额
     *
     * @return
     */
    @Override
    public PerformanceDetailVO getLastMonthStatisticsByMember(UnionOrderParams params) {
        PerformanceDetailVO performanceDetailVO = orderClient.getLastMonthStatisticsByMember(params);
        if (null == performanceDetailVO) {
            performanceDetailVO = new PerformanceDetailVO();
        }
        return performanceDetailVO;
    }

    /**
     * 审批工会成员
     *
     * @param unionId
     * @param memberId
     * @param status
     */
    @Override
    public void apply(String unionId, String memberId, String status) {
        RLock rLock = redissonClient.getLock("apply_" + memberId);
        try {
            rLock.lock();
            LambdaQueryWrapper<UnionMemberApply> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UnionMemberApply::getUnionId, unionId);
            queryWrapper.eq(UnionMemberApply::getMemberId, memberId);
            queryWrapper.last("limit 1");
            UnionMemberApply unionMemberApply = unionMemberApplyMapper.selectOne(queryWrapper);
            if (null != unionMemberApply) {
                unionMemberApply.setStatus(status);
                User user = userService.getById(memberId);
                if (UnionMemberStatusEnum.PASS.name().equals(status)) {
                    if (StringUtils.isNotEmpty(user.getUnionId())) {
                        if (user.getUnionId().equals(unionId)) {
                            throw new ServiceException("用户已加入该工会");
                        } else {
                            throw new ServiceException("用户已加入其他工会");
                        }
                    }

                    UnionMember unionMember = new UnionMember();
                    unionMember.setMemberId(memberId);
                    unionMember.setMemberName(user.getUsername());
                    unionMember.setJoinTime(new Date());
                    unionMember.setStatus(UnionMemberStatusEnum.PASS.name());
                    unionMember.setUnionId(unionId);
                    this.save(unionMember);

                    if (StringUtils.isNotEmpty(user.getOpenId())) {
                        OpenAppUser openAppUser = userApi.getUserinfoByOpenId(user.getOpenId());
                        if (null != openAppUser) {
                            List<PojoGroupMember> groupMemberList = Lists.newArrayList();
                            PojoGroupMember groupMember = new PojoGroupMember();
                            groupMember.setMember_id(openAppUser.getUId());
                            groupMember.setType(ProtoConstants.GroupMemberType.GroupMemberType_Normal);
                            groupMemberList.add(groupMember);

                            Union union = unionMapper.selectById(unionId);
                            addGroup(groupMemberList, union);
                        }
                    }


                    user.setUnionId(unionId);
                    userService.updateById(user);

                    UnionLog unionLog = UnionLog.builder()
                            .operationRemark("同意" + user.getUsername() + "加入工会")
                            .createTime(new Date())
                            .unionId(unionId)
                            .operationUserId(UserContext.getCurrentId())
                            .operationUserName(Objects.requireNonNull(UserContext.getCurrentUser()).getUsername())
                            .build();

                    applicationEventPublisher.publishEvent(
                            TransactionCommitSendMQEvent.builder()
                                    .source("UNION_LOG")
                                    .exchange(amqpExchangeProperties.getUnion())
                                    .routingKey(UnionRoutingKey.ADD_UNION_LOG)
                                    .message(unionLog)
                                    .build());
                } else {
                    UnionLog unionLog = UnionLog.builder()
                            .operationRemark("拒绝" + user.getUsername() + "加入工会")
                            .createTime(new Date())
                            .unionId(unionId)
                            .operationUserId(UserContext.getCurrentId())
                            .operationUserName(Objects.requireNonNull(UserContext.getCurrentUser()).getUsername())
                            .build();

                    applicationEventPublisher.publishEvent(
                            TransactionCommitSendMQEvent.builder()
                                    .source("UNION_LOG")
                                    .exchange(amqpExchangeProperties.getUnion())
                                    .routingKey(UnionRoutingKey.ADD_UNION_LOG)
                                    .message(unionLog)
                                    .build());
                }
            }
            this.unionMemberApplyMapper.updateById(unionMemberApply);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        } finally {
            rLock.unlock();
        }
    }

    public UnionMemberDetailDTO getDetailInfo(String memberId) {
        User user = userService.getById(memberId);
        if (null == user) {
            throw new ServiceException("用户不存在");
        }
        Union union = unionMapper.selectOne(new LambdaQueryWrapper<Union>().eq(Union::getChairmanId, memberId).last("limit 1"));

        UnionMember member = getByUnionMemberId(memberId);
        if (null == member && null == union) {
            return null;
        }

        UnionMemberDetailDTO data = new UnionMemberDetailDTO();
        if (null != union) {
            data.setChairmanFlag(1);
            data.setUnionId(union.getId());
            data.setJoinTime(union.getCreateTime());
            data.setUnionName(union.getUnionName());
            data.setCity(union.getCityName());
            data.setCityId(union.getCityId());

        } else if (null != member) {
            union = unionMapper.selectById(member.getUnionId());
            data.setChairmanFlag(0);
            data.setUnionId(member.getUnionId());
            data.setJoinTime(member.getJoinTime());
            if (null != union) {
                data.setUnionName(union.getUnionName());
                data.setCity(union.getCityName());
                data.setCityId(union.getCityId());
            }
        }
        data.setMemberName(user.getUsername());
        data.setMemberHead(user.getFace());

        //统计当前成员的下级人数，区分店主和非店主
        List<UnionMemberDetailDTO> childsCount = userService.countChilds(memberId);
        if (null != childsCount && !childsCount.isEmpty()) {
            for (UnionMemberDetailDTO item : childsCount) {
                if (item.getShopOwnerFlag() == 1) {
                    data.setShopOwnerCount(item.getUserCount()); //当前成员的下级店主数量
                } else {
                    data.setUserCount(item.getUserCount()); //当前成员的下级非店主数据
                }
            }
        }
        data.setChildCount(data.getUserCount() + data.getShopOwnerCount());//当前成员的所有下级人数

        Date monthStart = DateUtil.beginOfMonth(new Date());
        Date monthEnd = DateUtil.endOfMonth(new Date());
        String startTime = DateUtil.format(monthStart, "yyyy-MM-dd HH:mm:ss");
        String endTime = DateUtil.format(monthEnd, "yyyy-MM-dd HH:mm:ss");
        //当前成员本月的业绩和订单数量
        OrderItemViewVO m1 = orderItemClient.getDistributionFlowPriceAndComissTotalByMonth(memberId, startTime, endTime);

        if (null != m1) {
            data.setMonthMoney(m1.getFlowPrice());//本月业绩
            data.setMonthOrderSum(m1.getOrderSum()); //本月订单数量
            data.setMonthTradeCount(m1.getSubOrderSum()); //下级成交人数
        }
        Date lastMonth = DateUtil.lastMonth();
        Date lastMonthStart = DateUtil.beginOfMonth(lastMonth);
        Date lastMonthEnd = DateUtil.endOfMonth(lastMonth);
        String lastStartTime = DateUtil.format(lastMonthStart, "yyyy-MM-dd HH:mm:ss");
        String lastEndTime = DateUtil.format(lastMonthEnd, "yyyy-MM-dd HH:mm:ss");
        //当前成员上月的业绩和订单数量
        OrderItemViewVO m2 = orderItemClient.getDistributionFlowPriceAndComissTotalByMonth(memberId, lastStartTime, lastEndTime);

        if (null != m2) {
            data.setLastMonthMoney(m2.getFlowPrice());//上月业绩
            data.setLastMonthOrderSum(m2.getOrderSum()); //上月订单数量
            data.setLastMonthTradeCount(m2.getSubOrderSum()); //上月下级成交人数
        }
        //查询运营中心名称
        OperationCenter operationCenter = operationCenterClient.getByAddressId(union.getProvinceId());
        if (operationCenter != null && StrUtil.isNotEmpty(operationCenter.getOperationName())) {
            data.setOperationCenterName(operationCenter.getOperationName());
        }
//
//        if(null!=union){
//            data.setUnionId(union.getId());
//            data.setChairmanFlag(union.getChairmanId().equals(memberId)?1:0);
//        }
        return data;
    }


    public UnionMember getUnionChairman(String unionId) {
        Union union = unionMapper.getUnionInfo(unionId);
        UnionMember unionMember = new UnionMember();
        unionMember.setMemberId(union.getChairmanId());
        unionMember.setMemberName(union.getChairmanName());
        unionMember.setMemberHead(union.getChairmanPortrait());
        return unionMember;
    }


    /**
     * 获取工会下的成员ID
     *
     * @param unionId
     * @return
     */
    public List<UnionMember> getMemberIdList(String unionId) {
        LambdaQueryWrapper<UnionMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UnionMember::getUnionId, unionId);
        queryWrapper.select(UnionMember::getUnionId, UnionMember::getMemberId);
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 获取运行中心省份id  --》 获取省份下的工会 ---》 获取工会下的店主
     *
     * @return 店主数量统计
     */
    @Override
    public ResultMessage<HomeResult> shopkeeperStatistics() {
        HomeResult homeResult = HomeResultUtil.createDefaultValue();
        /*DistributionVO distributionVO = new DistributionVO();
        distributionVO.setPageNumber(1);
        distributionVO.setPageSize(10000000);
        List<Distribution> unionMemberList = distributionClient.getListByDistribution(distributionVO);
        if (CollectionUtil.isEmpty(unionMemberList)) {
            return ResultUtil.data(homeResult);
        }*/

        OperationCenter operationCenter = operationCenterClient.getOperationCenter(UserContext.getCurrentUser().getId());
        if (null == operationCenter) {
            return ResultUtil.data(homeResult);
        }
        LambdaQueryWrapper<Union> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Union::getProvinceId, operationCenter.getProvinceId());
        List<Union> unionList = unionMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(unionList)) {
            return ResultUtil.data(homeResult);
        }

        LambdaQueryWrapper<UnionMember> memberQueryWrapper = new LambdaQueryWrapper<>();
        memberQueryWrapper.in(UnionMember::getUnionId, unionList.stream().map(Union::getId).collect(Collectors.toList()));
        List<UnionMember> unionMemberList = this.baseMapper.selectList(memberQueryWrapper);
        if (unionMemberList.isEmpty()) {
            unionMemberList = new ArrayList<>();
        }

        for (Union union : unionList) {
            UnionMember unionMember = new UnionMember();
            unionMember.setUnionId(union.getId());
            unionMember.setMemberId(union.getChairmanId());
            unionMember.setJoinTime(union.getCreateTime());
            unionMemberList.add(unionMember);
        };

        //计算返回值
        homeResult = HomeResultUtil.createResult(unionMemberList, unionMember -> {
            Date createDate = unionMember.getJoinTime();
            return createDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        });
        return ResultUtil.data(homeResult);
    }

    /**
     * @return 获取运营商下面的已加入工会的店主
     */
    @Override
    public List<Distribution> getUnionMemberPage(DistributionVO distributionVO) {
        LambdaQueryWrapper<Distribution> memberLambdaQueryWrapper = this.createQueryWrapper();
        if (memberLambdaQueryWrapper == null) {
            return new ArrayList<>();
        }
        if (StringUtils.isNotEmpty(distributionVO.getId())) {
            memberLambdaQueryWrapper.eq(Distribution::getId, distributionVO.getId());
        }
        if (StringUtils.isNotEmpty(distributionVO.getMemberName())) {
            List<Distribution> listByName = distributionClient.getListByName(distributionVO.getMemberName());
            if (CollectionUtil.isEmpty(listByName)) {
                memberLambdaQueryWrapper.eq(Distribution::getId, -1);
            } else {
                memberLambdaQueryWrapper.in(Distribution::getMemberId, listByName.stream().map(Distribution::getMemberId).collect(Collectors.toList()));
            }
        }
        if (StringUtils.isNotEmpty(distributionVO.getUnionName())) {
            LambdaQueryWrapper<Union> unionLambdaQueryWrapper = new LambdaQueryWrapper<>();
            unionLambdaQueryWrapper.like(Union::getUnionName, distributionVO.getUnionName());
            unionLambdaQueryWrapper.select(Union::getId);
            List<Union> unionList = unionMapper.selectList(unionLambdaQueryWrapper);
            if (CollectionUtil.isEmpty(unionList)) {
                memberLambdaQueryWrapper.eq(Distribution::getId, -1);
            } else {
                memberLambdaQueryWrapper.in(Distribution::getMemberId, unionList.stream().map(Union::getChairmanId).collect(Collectors.toList()));
            }
        }
        memberLambdaQueryWrapper.eq(Distribution::getDistributionStatus, DistributionStatusEnum.PASS.name());
        memberLambdaQueryWrapper.orderByDesc(Distribution::getCreateTime);
        //获取店主列表
        return distributionClient.getList(distributionVO);
    }

//    @Override
//    public List<UnionMember> getUnionMemberList() {
//        LambdaQueryWrapper<UnionMember> memberLambdaQueryWrapper = this.createQueryWrapper();
//        if (memberLambdaQueryWrapper == null) {
//            return new ArrayList<>();
//        }
//        return super.list(memberLambdaQueryWrapper);
//    }

    /**
     * 根据类型，获取运营商下面的已加入工会的店主
     *
     * @param type 类型 1今日，2昨日......
     * @return 新增店主数量
     */
    public Long numberOfNewOwners(Integer type, LambdaQueryWrapper<UnionMember> queryWrapper) {
        if (type == null) {
            throw new ServiceException("type类型为空");
        }
        if (queryWrapper == null) {
            return 0L;
        }
        // 1. 今日
        if (type.equals(CommonConstant.SHOPKEEPER_TYPE_01)) {
            queryWrapper.apply("TO_DAYS(create_time) = TO_DAYS(NOW())");
        }
        // 2. 昨日
        if (type.equals(CommonConstant.SHOPKEEPER_TYPE_02)) {
            queryWrapper.apply("TO_DAYS(create_time) = TO_DAYS(NOW() - INTERVAL 1 DAY)");
        }
        // 3. 本周
        LocalDate firstDayOfWeek = LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate lastDayOfWeek = LocalDate.now().with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
        if (type.equals(CommonConstant.SHOPKEEPER_TYPE_03)) {
            queryWrapper.between(UnionMember::getCreateTime, firstDayOfWeek, lastDayOfWeek);
        }
        if (type.equals(CommonConstant.SHOPKEEPER_TYPE_04)) {
            // 4. 上周
            LocalDate firstDayOfLastWeek = firstDayOfWeek.minusDays(7);
            LocalDate lastDayOfLastWeek = lastDayOfWeek.minusDays(7);
            queryWrapper.between(UnionMember::getCreateTime, firstDayOfLastWeek, lastDayOfLastWeek);
        }
        // 5. 本月
        LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
        LocalDate lastDayOfMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
        if (type.equals(CommonConstant.SHOPKEEPER_TYPE_05)) {
            queryWrapper.between(UnionMember::getCreateTime, firstDayOfMonth, lastDayOfMonth);
        }
        // 6. 上月
        if (type.equals(CommonConstant.SHOPKEEPER_TYPE_06)) {
            LocalDate firstDayOfLastMonth = firstDayOfMonth.minusMonths(1);
            LocalDate lastDayOfLastMonth = lastDayOfMonth.minusMonths(1);
            queryWrapper.between(UnionMember::getCreateTime, firstDayOfLastMonth, lastDayOfLastMonth);
        }
        // 7. 本季度
        LocalDate now = LocalDate.now();
        LocalDate firstDayOfQuarter = now.with(now.getMonth().firstMonthOfQuarter()).with(TemporalAdjusters.firstDayOfMonth());
        LocalDate lastDayOfQuarter = firstDayOfQuarter.plusMonths(2).with(TemporalAdjusters.lastDayOfMonth());
        if (type.equals(CommonConstant.SHOPKEEPER_TYPE_07)) {
            queryWrapper.between(UnionMember::getCreateTime, firstDayOfQuarter, lastDayOfQuarter);
        }
        // 8. 上季度
        if (type.equals(CommonConstant.SHOPKEEPER_TYPE_08)) {
            LocalDate firstDayOfLastQuarter = firstDayOfQuarter.minusMonths(3);
            LocalDate lastDayOfLastQuarter = firstDayOfQuarter.minusDays(1);
            queryWrapper.between(UnionMember::getCreateTime, firstDayOfLastQuarter, lastDayOfLastQuarter);
        }
        // 9. 今年
        LocalDate firstDayOfYear = LocalDate.now().with(TemporalAdjusters.firstDayOfYear());
        LocalDate lastDayOfYear = LocalDate.now().with(TemporalAdjusters.lastDayOfYear());
        if (type.equals(CommonConstant.SHOPKEEPER_TYPE_09)) {
            queryWrapper.between(UnionMember::getCreateTime, firstDayOfYear, lastDayOfYear);
        }
        // 10. 去年
        if (type.equals(CommonConstant.SHOPKEEPER_TYPE_10)) {
            LocalDate firstDayOfLastYear = firstDayOfYear.minusYears(1);
            LocalDate lastDayOfLastYear = lastDayOfYear.minusYears(1);
            queryWrapper.between(UnionMember::getCreateTime, firstDayOfLastYear, lastDayOfLastYear);
        }
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public NumberOfOwners numberOfOwners(Integer type) {
        NumberOfOwners numberOfOwners = new NumberOfOwners();
        LambdaQueryWrapper<Distribution> memberLambdaQueryWrapper = this.createQueryWrapper();
        if (memberLambdaQueryWrapper == null) {
            return numberOfOwners;
        }
//        NumberOfOwnersReq numberOfOwnersReq = new NumberOfOwnersReq();
        numberOfOwners.setTotalNumber(distributionClient.getCountByWrapper().doubleValue());
//        numberOfOwnersReq.setType(type);
        numberOfOwners.setTypeNumber(distributionClient.getCountByTypeWrapper(type).doubleValue());

        AuthUser authUser = UserContext.getCurrentUser();
        if (authUser == null) {
            throw new ServiceException("请先登录后重试");
        }
        //获取运行中心省份id
        OperationCenter operationCenter = operationCenterClient.getOperationCenter(authUser.getId());
        if (operationCenter == null) {
            throw new ServiceException("未获取到，运营中心信息");
        }

        LambdaQueryWrapper<UnionMember> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Union> unionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (type != null) {
            // 1. 今日
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_01)) {
                queryWrapper.apply("TO_DAYS(join_time) = TO_DAYS(NOW())");
                unionLambdaQueryWrapper.apply("TO_DAYS(create_time) = TO_DAYS(NOW())");
            }
            // 2. 昨日
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_02)) {
                queryWrapper.apply("TO_DAYS(join_time) = TO_DAYS(NOW() - INTERVAL 1 DAY)");
                unionLambdaQueryWrapper.apply("TO_DAYS(create_time) = TO_DAYS(NOW() - INTERVAL 1 DAY)");
            }
            // 3. 本周
            LocalDate firstDayOfWeek = LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
            LocalDate lastDayOfWeek = LocalDate.now().with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_03)) {
                queryWrapper.between(UnionMember::getJoinTime, firstDayOfWeek, lastDayOfWeek);
                unionLambdaQueryWrapper.between(Union::getCreateTime, firstDayOfWeek, lastDayOfWeek);
            }
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_04)) {
                // 4. 上周
                LocalDate firstDayOfLastWeek = firstDayOfWeek.minusDays(7);
                LocalDate lastDayOfLastWeek = lastDayOfWeek.minusDays(7);
                queryWrapper.between(UnionMember::getJoinTime, firstDayOfLastWeek, lastDayOfLastWeek);
                unionLambdaQueryWrapper.between(Union::getCreateTime, firstDayOfLastWeek, lastDayOfLastWeek);
            }
            // 5. 本月
            LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
            LocalDate lastDayOfMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_05)) {
                queryWrapper.between(UnionMember::getJoinTime, firstDayOfMonth, lastDayOfMonth);
                unionLambdaQueryWrapper.between(Union::getCreateTime, firstDayOfMonth, lastDayOfMonth);
            }
            // 6. 上月
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_06)) {
                LocalDate firstDayOfLastMonth = firstDayOfMonth.minusMonths(1);
                LocalDate lastDayOfLastMonth = lastDayOfMonth.minusMonths(1);
                queryWrapper.between(UnionMember::getJoinTime, firstDayOfLastMonth, lastDayOfLastMonth);
                unionLambdaQueryWrapper.between(Union::getCreateTime, firstDayOfLastMonth, lastDayOfLastMonth);
            }
            // 7. 本季度
            LocalDate now = LocalDate.now();
            LocalDate firstDayOfQuarter = now.with(now.getMonth().firstMonthOfQuarter()).with(TemporalAdjusters.firstDayOfMonth());
            LocalDate lastDayOfQuarter = firstDayOfQuarter.plusMonths(2).with(TemporalAdjusters.lastDayOfMonth());
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_07)) {
                queryWrapper.between(UnionMember::getJoinTime, firstDayOfQuarter, lastDayOfQuarter);
                unionLambdaQueryWrapper.between(Union::getCreateTime, firstDayOfQuarter, lastDayOfQuarter);
            }
            // 8. 上季度
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_08)) {
                LocalDate firstDayOfLastQuarter = firstDayOfQuarter.minusMonths(3);
                LocalDate lastDayOfLastQuarter = firstDayOfQuarter.minusDays(1);
                queryWrapper.between(UnionMember::getJoinTime, firstDayOfLastQuarter, lastDayOfLastQuarter);
                unionLambdaQueryWrapper.between(Union::getCreateTime, firstDayOfLastQuarter, lastDayOfLastQuarter);
            }
            // 9. 今年
            LocalDate firstDayOfYear = LocalDate.now().with(TemporalAdjusters.firstDayOfYear());
            LocalDate lastDayOfYear = LocalDate.now().with(TemporalAdjusters.lastDayOfYear());
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_09)) {
                queryWrapper.between(UnionMember::getJoinTime, firstDayOfYear, lastDayOfYear);
                unionLambdaQueryWrapper.between(Union::getCreateTime, firstDayOfYear, lastDayOfYear);
            }
            // 10. 去年
            if (type.equals(CommonConstant.SHOPKEEPER_TYPE_10)) {
                LocalDate firstDayOfLastYear = firstDayOfYear.minusYears(1);
                LocalDate lastDayOfLastYear = lastDayOfYear.minusYears(1);
                queryWrapper.between(UnionMember::getJoinTime, firstDayOfLastYear, lastDayOfLastYear);
                unionLambdaQueryWrapper.between(Union::getCreateTime, firstDayOfLastYear, lastDayOfLastYear);
            }
        }
        unionLambdaQueryWrapper.eq(Union::getProvinceId, operationCenter.getProvinceId());
        List<Union> unionList = unionMapper.selectList(unionLambdaQueryWrapper);
        if (!unionList.isEmpty()) {
            queryWrapper.in(UnionMember::getUnionId, unionList.stream().map(Union::getId).toList());
            long memberCount = this.count(queryWrapper) + unionList.size();
            numberOfOwners.setTypeNumber((double) memberCount);
        }else {
            numberOfOwners.setTypeNumber((double) unionList.size());
        }


        LambdaQueryWrapper<Union> unionLambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        unionLambdaQueryWrapper2.eq(Union::getProvinceId, operationCenter.getProvinceId());
        List<Union> unionList2 = unionMapper.selectList(unionLambdaQueryWrapper2);

        LambdaQueryWrapper<UnionMember> queryWrapper2 = new LambdaQueryWrapper<>();
        if (!unionList2.isEmpty()) {
            queryWrapper2.in(UnionMember::getUnionId, unionList2.stream().map(Union::getId).toList());
            long memberCount = this.count(queryWrapper2) + unionList2.size();
            numberOfOwners.setTotalNumber((double) memberCount);
        }else {
            numberOfOwners.setTotalNumber((double) unionList2.size());
        }
        return numberOfOwners;
    }

    /**
     * 根据类型，获取运营商下面的已加入工会的店主 ==>  业绩
     *
     * @param type 类型 1今日，2昨日......
     * @return 新增业绩数 + 总数
     */
    @Override
    public NumberOfOwners shopOwnersTurnover(Integer type) {
        NumberOfOwners numberOfOwners = new NumberOfOwners();
        if (type == null) {
            throw new ServiceException("type类型为空");
        }
        //根据类型 1今日，2昨日...... 查询
        AuthUser authUser = UserContext.getCurrentUser();
        if (authUser == null) {
            throw new ServiceException("请先登录后重试");
        }
        //获取运行中心省份id
        OperationCenter operationCenter = operationCenterClient.getOperationCenter(authUser.getId());
        if (operationCenter == null) {
            throw new ServiceException("未获取到，运营中心信息");
        }
        //获取省份下的工会
        LambdaQueryWrapper<Union> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Union::getProvinceId, operationCenter.getProvinceId());
        queryWrapper.select(Union::getId);
        List<Union> unionList = unionMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(unionList)) {
            return null;
        }
        List<String> unionIdList = unionList.stream().map(Union::getId).toList();
        NumberOfOwnerDTO dto = new NumberOfOwnerDTO();
        dto.setUnionIdlist(unionIdList);
        //查询工会对应店主的总业绩
        BigDecimal totalPrice = baseMapper.selectOrderTotalPrice(dto);
        numberOfOwners.setTotalNumber(totalPrice != null ? totalPrice.doubleValue() : 0.0);
        //处理参数
        this.processParam(dto, type);
        BigDecimal statisticsPrice = baseMapper.selectOrderTotalPrice(dto);
        //新增业绩
        numberOfOwners.setTypeNumber(statisticsPrice != null ? statisticsPrice.doubleValue() : 0.0);
        return numberOfOwners;
    }

    /**
     * 参数处理
     * 注： 这里条件判断的结束时间一定要用 < ， 而不是 <=
     *
     * @return
     */
    private void processParam(NumberOfOwnerDTO dto, Integer type) {
        LocalDate dateparam = LocalDate.now();
        switch (type) {
            //今日
            case 1:
                //开始时间
                dto.setStartTime(dateparam.atStartOfDay());
                //结束时间
                dto.setEndTime(dto.getStartTime().plusDays(1));
                break;
            //昨天
            case 2:
                dateparam = dateparam.minusDays(1);
                //开始时间
                dto.setStartTime(dateparam.atStartOfDay());
                //结束时间
                dto.setEndTime(dto.getStartTime().plusDays(1));
                break;
            //本周
            case 3:
                //获取本周第一天
                dateparam = dateparam.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
                //开始时间
                dto.setStartTime(dateparam.atStartOfDay());
                //本周最后一天的结束时间
//                    dto.setEndTime(dateparam.plusDays(6).atTime(LocalTime.MAX));
                dto.setEndTime(dto.getStartTime().plusWeeks(1));
                break;
            //上周
            case 4:
                //获取上周第一天
                dateparam = dateparam.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).minusWeeks(1);
                //开始时间
                dto.setStartTime(dateparam.atStartOfDay());
                //本周最后一天的结束时间
                dto.setEndTime(dto.getStartTime().plusWeeks(1));
                break;
            //本月
            case 5:
                //获取本月第一天
                dateparam = YearMonth.now().atDay(1);
                //开始时间
                dto.setStartTime(dateparam.atStartOfDay());
                //本月最后一天的结束时间,这里就取当前时间,取未来时间没意义
                dto.setEndTime(LocalDateTime.now().plusHours(1));
                break;
            //上月
            case 6:
                // 获取上个月的年份和月份
                YearMonth lastMonth = YearMonth.now().minusMonths(1);
                //开始时间
                dto.setStartTime(lastMonth.atDay(1).atStartOfDay());
                //上月最后一天的结束时间
                dto.setEndTime(dto.getStartTime().plusMonths(1));
                break;
            //本季度
            case 7:
                //开始时间
                dto.setStartTime(ToolUtil.getStartOrEndDayOfQuarter(LocalDate.now(), false).atStartOfDay());
                //本季度最后一天的结束时间
                dto.setEndTime(LocalDateTime.now().plusHours(1));
                break;
            //上季度
            case 8:
                //开始时间
                dto.setStartTime(ToolUtil.getStartOrEndDayOfQuarter(LocalDate.now(), false).minusMonths(3).atStartOfDay());
                //本季度最后一天的结束时间
                dto.setEndTime(ToolUtil.getStartOrEndDayOfQuarter(LocalDate.now(), false).atStartOfDay());
                break;
            //今年
            case 9:
                // 获取今年的年份
                int year = Year.now().getValue();
                // 获取今年的第一个月份
                Month firstMonthOfYear = Month.JANUARY;
                // 构造今年的开始时间（00:00:00）
                LocalDateTime startOfYear = LocalDateTime.of(year, firstMonthOfYear, 1, 0, 0, 0);
                //开始时间
                dto.setStartTime(startOfYear);
                //最后一天的结束时间
                dto.setEndTime(dto.getStartTime().plusYears(1));
                break;
            //去年
            case 10:
                // 获取去年的年份
                int lastYear = Year.now().getValue() - 1;
                // 获取去年的第一个月份
                Month firstMonthOfLastYear = Month.JANUARY;
                // 构造去年的开始时间（00:00:00）
                LocalDateTime startOfLastYear = LocalDateTime.of(lastYear, firstMonthOfLastYear, 1, 0, 0, 0);
                //开始时间
                dto.setStartTime(startOfLastYear);
                //最后一天的结束时间
                dto.setEndTime(dto.getStartTime().plusYears(1));
                break;
            default:
        }
    }

    public static void main(String[] args) {
        System.out.println(ToolUtil.getStartOrEndDayOfQuarter(LocalDate.now(), false));
    }

    public LambdaQueryWrapper<Distribution> createQueryWrapper() {
        AuthUser authUser = UserContext.getCurrentUser();
        if (authUser == null) {
            throw new ServiceException("请先登录后重试");
        }
        //获取运行中心省份id
        OperationCenter operationCenter = operationCenterClient.getOperationCenter(authUser.getId());
        if (operationCenter == null) {
            throw new ServiceException("未获取到，运营中心信息");
        }
        //获取省份下的工会
        LambdaQueryWrapper<Union> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Union::getProvinceId, operationCenter.getProvinceId());
        queryWrapper.select(Union::getId, Union::getChairmanId);
        List<Union> unionList = unionMapper.selectList(queryWrapper);
        LambdaQueryWrapper<Distribution> distributionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (CollectionUtil.isEmpty(unionList)) {
            return null;
        }
        //获取工会下的店主
        List<String> unionIdList = unionList.stream().map(Union::getId).toList();
        LambdaQueryWrapper<UnionMember> memberLambdaQueryWrapper = new LambdaQueryWrapper<>();
        memberLambdaQueryWrapper.in(UnionMember::getUnionId, unionIdList);
        memberLambdaQueryWrapper.orderByDesc(UnionMember::getCreateTime);
        memberLambdaQueryWrapper.select(UnionMember::getId, UnionMember::getJoinTime, UnionMember::getUnionId, UnionMember::getCreateTime, UnionMember::getMemberId);
        List<UnionMember> unionMemberList = super.list(memberLambdaQueryWrapper);
        if (CollectionUtil.isNotEmpty(unionMemberList)) {
            distributionLambdaQueryWrapper.and(q ->
                    q.in(Distribution::getMemberId, unionList.stream().map(Union::getChairmanId).toList()).or()
                            .in(Distribution::getMemberId, unionMemberList.stream().map(UnionMember::getMemberId).toList())
            );
        } else {
            distributionLambdaQueryWrapper.in(Distribution::getMemberId, unionList.stream().map(Union::getChairmanId).toList());
        }
        return distributionLambdaQueryWrapper;
    }


}
